# coding=utf-8
# 编译日期：2022-09-17 17:11:20
# 版权所有：www.i-search.com.cn
import ubpa.init_input as iinput
from ubpa.base_util import StdOutHook, ExceptionHandler
import ubpa.ibox as ibox
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.base import MIMEBase
from email import encoders
import smtplib


import datetime
import pandas as pd
import os
import openpyxl
import datetime 
import ubpa.ichrome_firefox as ichrome_firefox
import ubpa.ikeyboard as ikeyboard
import os
import ubpa.iie as iie
import pandas as pd
import time
import pdb
from ubpa.ilog import ILog
from ubpa.base_img import set_img_res_path
import getopt
from sys import argv
import sys
from base_img import *

class RpaAsiM:
     
    def __init__(self,**kwargs):
        self.__logger = ILog(__file__)
        self.path = set_img_res_path(__file__)
        self.robot_no = ''
        self.proc_no = ''
        self.job_no = ''
        self.input_arg = ''
        if('robot_no' in kwargs.keys()):
            self.robot_no = kwargs['robot_no']
        if('proc_no' in kwargs.keys()):
            self.proc_no = kwargs['proc_no']
        if('job_no' in kwargs.keys()):
            self.job_no = kwargs['job_no']
        ILog.JOB_NO, ILog.OLD_STDOUT = self.job_no, sys.stdout
        sys.stdout = StdOutHook(self.job_no, sys.stdout)
        ExceptionHandler.JOB_NO, ExceptionHandler.OLD_STDERR = self.job_no, sys.stderr
        sys.excepthook = ExceptionHandler.handle_exception
        if('input_arg' in kwargs.keys()):
            self.input_arg = kwargs['input_arg']
            if(len(self.input_arg) <= 0):
                self.input_arg = iinput.load_init(__file__)
            if self.input_arg is None:
                sys.exit(0)
      
    def salary(self):
        lv_path=None
        # For循环
        self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:salary,StepNodeTag:20220917153818804192,Title:For循环,Note:## 3次循环，保证输入目录正确')
        for iTimes in range(3):
            # Try异常
            self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:salary,StepNodeTag:20220917153818804191,Title:Try异常,Note:')
            try:
                #输入框
                self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:salary,StepNodeTag:20220917153818804189,Title:输入框,Note:# 输入目标文件所在文件夹')
                lv_path=ibox.input_box(text='工资：请输入目标excel和临时excel的目录:')
                print('[salary] [输入框] [SNTag:20220917153818804189]  返回值：[' + str(type(lv_path)) + ']' + str(lv_path))
                #代码块
                self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:salary,StepNodeTag:20220917153818804185,Title:代码块,Note:# 判断目标文件是否存在')
                isExist = False
                lv_outText = ''
                ## 判断输入是否为已存在文件夹
                if os.path.isdir(lv_path):
                    if os.path.isfile(lv_path + '\员工工资表.xlsx') & os.path.isfile(lv_path + '\员工基本信息表.xlsx') & os.path.isfile(lv_path + '\员工考勤表.xlsx'):
                        isExist = True
                    else:
                        lv_outText = '输入的文件夹中w文件“员工工资表”、“员工基本信息表”、“员工考勤表”不全'
                else:
                    ## 输入不是文件夹
                    lv_outText = '输入内容不是文件夹'
                    
                    
                
                
                # IF分支
                self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:salary,StepNodeTag:20220917153818804186,Title:IF分支,Note:')
                if isExist:
                    # Break中断
                    self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:salary,StepNodeTag:20220917153818804184,Title:Break中断,Note:')
                    break
                else:
                    #消息框
                    self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:salary,StepNodeTag:20220917153818804187,Title:消息框,Note:')
                    tvar_20220917153818804188=ibox.msgs_box(lv_outText,title=r'提示',timeout=0)
                    print('[salary] [消息框] [SNTag:20220917153818804187]  返回值：[' + str(type(tvar_20220917153818804188)) + ']' + str(tvar_20220917153818804188))
            except Exception as e:
                # Continue继续
                self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:salary,StepNodeTag:20220917153818804183,Title:Continue继续,Note:')
                continue
            finally:
                pass
        #代码块
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:salary,StepNodeTag:20220916082148811350,Title:代码块,Note:# 读取相关excel')
        time.sleep(2)
        data_sa = pd.read_excel(lv_path + '\员工工资表.xlsx')
        data_info = pd.read_excel(lv_path + '\员工基本信息表.xlsx')
        data_attend = pd.read_excel(lv_path + '\员工考勤表.xlsx')
        
        #代码块
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:salary,StepNodeTag:20220916082320364356,Title:代码块,Note:# 处理、合并excel')
        time.sleep(2)
        ### 剔除无用列
        data_info.pop('年龄')
        data_info.pop('职位')
        data_attend.pop('姓名')
        
        ### 合并excel
        data = pd.merge(data_info, data_sa,how='left', on='工号')
        data = pd.merge(data, data_attend,how='left', on='工号')
        #代码块
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:salary,StepNodeTag:20220916084004166375,Title:代码块,Note:# 计算目标excel')
        lst_salary = []
        lst_deduct = []
        # 计算扣款、实发工资
        for index,row in data.iterrows():
            iDeduct = int(row['迟到次数']) * 50
            iSalary = int(row['应发工资']) - iDeduct
            lst_salary.append(iSalary)
            lst_deduct.append(iDeduct)
            
        data['考勤扣款'] = lst_deduct
        data['实发工资'] = lst_salary
        data.pop('迟到次数')
        # 排序
        sort_data = data.sort_values(by='工号')
        
        #代码块
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:salary,StepNodeTag:20220916085809900377,Title:代码块,Note:# 保存目标excel')
        sort_data.to_excel(lv_path + '\员工实发工资表.xlsx',index=False)
      
    def weather(self):
        lv_datetime=None
        lv_temperature=None
        lv_rain=None
        lv_wind=None
        lv_tempTable=None
        lv_table1=None
        lv_path=None
        lv_outTxt=None
        #代码块
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:2022091714433262875,Title:代码块,Note:')
        lv_outTxt= ''
        # For循环
        self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:weather,StepNodeTag:2022091714291486333,Title:For循环,Note:## 3次循环，保证输入目录正确')
        for iTimes in range(3):
            # Try异常
            self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:weather,StepNodeTag:2022091714303258337,Title:Try异常,Note:')
            try:
                #输入框
                self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:2022091714313365248,Title:输入框,Note:# 输入目标文件所在文件夹')
                lv_path=ibox.input_box(text='天气：请输入目标excel和临时excel的目录:')
                print('[weather] [输入框] [SNTag:2022091714313365248]  返回值：[' + str(type(lv_path)) + ']' + str(lv_path))
                #代码块
                self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:2022091714321739754,Title:代码块,Note:# 判断目标文件是否存在')
                isExist = False
                lv_outText = ''
                ## 判断输入是否为已存在文件夹
                if os.path.isdir(lv_path):
                    if os.path.isfile(lv_path + '\城市及对应出差员工信息表.xlsx'):
                        isExist = True
                    else:
                        lv_outText = '输入的文件夹中不包含“市及对应出差员工信息表.xlsx”文件'
                else:
                    ## 输入不是文件夹
                    lv_outText = '输入内容不是文件夹'
                    
                    
                
                
                # IF分支
                self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:weather,StepNodeTag:2022091714405564661,Title:IF分支,Note:')
                if isExist:
                    # Break中断
                    self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:weather,StepNodeTag:2022091714411601064,Title:Break中断,Note:')
                    break
                else:
                    #消息框
                    self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:2022091714424161067,Title:消息框,Note:')
                    tvar_2022091714424161068=ibox.msgs_box(lv_outText,title=r'提示',timeout=0)
                    print('[weather] [消息框] [SNTag:2022091714424161067]  返回值：[' + str(type(tvar_2022091714424161068)) + ']' + str(tvar_2022091714424161068))
            except Exception as e:
                # Continue继续
                self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:weather,StepNodeTag:2022091714412244966,Title:Continue继续,Note:')
                continue
            finally:
                pass
        #代码块
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220916081744591303,Title:代码块,Note:# 读取目标EXCEL')
        time.sleep(2)
        data = pd.read_excel(lv_path + '\城市及对应出差员工信息表.xlsx')
        
        # 先关闭chrome
        cmd = "taskkill /f /t /im {}".format('chrome.exe')
        
        os.system(cmd)
        #网站
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:2022091714530588381,Title:网站,Note:# 打开chrome')
        iie.open_url(ie_path='C:/Program Files/Google/Chrome/Application/chrome.exe',url='https://weather.cma.cn/')
        #模拟按键
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:2022091714540542690,Title:模拟按键,Note:## 去掉可能的提示')
        time.sleep(1)
        ikeyboard.key_send_cs(waitfor=10.000,text='{Enter}')
        # For循环
        self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:weather,StepNodeTag:20220916081744591307,Title:For循环,Note:遍历excel')
        for index in data.index:
            #代码块
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220916081744591288,Title:代码块,Note:获取用户信息')
            cityname = str(data.iloc[index]['城市名称'])
            t_mail = str(data.iloc[index]['邮箱'])
            staff_name = str(data.iloc[index]['员工姓名'])
            
            
            
            #鼠标点击
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220917145703619113,Title:鼠标点击,Note:')
            time.sleep(1)
            ichrome_firefox.do_click_pos_chrome(waitfor=10.000,run_mode='unctrl',button='left',curson='center',continue_on_error='break',url=r'https://weather.cma.cn/.*',attrMap={"hasReachedRelativeAncestor":"false","nodeHierarchyInfo":[{"isPresentInSelector":1,"otherAttributes":{},"selectorInfo":{"attributes":{"css-selector":"#searchInput","tag":"INPUT","type":"text","xpath":"//*[@id=\"searchInput\"]"},"index":0,"tagName":"INPUT"}}]})
            #设置文本
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:2022091714543965797,Title:设置文本,Note:')
            time.sleep(1)
            ichrome_firefox.set_element_val_chrome(waitfor=10.000,text=cityname,url=r'https://weather.cma.cn/.*',attrMap={"hasReachedRelativeAncestor":"false","nodeHierarchyInfo":[{"isPresentInSelector":1,"otherAttributes":{},"selectorInfo":{"attributes":{"css-selector":"#searchInput","tag":"INPUT","type":"text","xpath":"//*[@id=\"searchInput\"]"},"index":0,"tagName":"INPUT"}}]})
            #模拟按键
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220917145733286118,Title:模拟按键,Note:')
            time.sleep(1)
            ikeyboard.key_send_cs(waitfor=10.000,text='{Space}')
            time.sleep(1)
            #模拟按键
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220917150700926140,Title:模拟按键,Note:')
            time.sleep(1)
            ikeyboard.key_send_cs(waitfor=10.000,text='{Enter}')
            time.sleep(1)
            #获取文本
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220916081744591293,Title:获取文本,Note:')
            lv_datetime=ichrome_firefox.get_element_val_chrome(waitfor=10.000,title=r'中国气象局-天气预报-城市预报',url=r'https://weather.cma.cn/.*',continue_on_error='break',attrMap={"hasReachedRelativeAncestor":"false","nodeHierarchyInfo":[{"isPresentInSelector":1,"otherAttributes":{},"selectorInfo":{"attributes":{"css-selector":"#pubtime","id":"pubtime","tag":"DIV","xpath":"//*[@id=\"pubtime\"]"},"index":0,"tagName":"DIV"}}]})
            print('[weather] [获取文本] [SNTag:20220916081744591293]  返回值：[' + str(type(lv_datetime)) + ']' + str(lv_datetime))
            #获取文本
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220916081744591298,Title:获取文本,Note:')
            lv_temperature=ichrome_firefox.get_element_val_chrome(waitfor=10.000,title=r'中国气象局-天气预报-城市预报',url=r'https://weather.cma.cn/.*',continue_on_error='break',attrMap={"hasReachedRelativeAncestor":"false","nodeHierarchyInfo":[{"isPresentInSelector":1,"otherAttributes":{},"selectorInfo":{"attributes":{"css-selector":"#temperature","id":"temperature","tag":"SPAN","xpath":"//*[@id=\"temperature\"]"},"index":0,"tagName":"SPAN"}}]})
            print('[weather] [获取文本] [SNTag:20220916081744591298]  返回值：[' + str(type(lv_temperature)) + ']' + str(lv_temperature))
            #获取文本
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220916081744591285,Title:获取文本,Note:')
            lv_rain=ichrome_firefox.get_element_val_chrome(waitfor=10.000,title=r'中国气象局-天气预报-城市预报',url=r'https://weather.cma.cn/.*',continue_on_error='break',attrMap={"hasReachedRelativeAncestor":"false","nodeHierarchyInfo":[{"isPresentInSelector":1,"otherAttributes":{},"selectorInfo":{"attributes":{"css-selector":"#precipitation","id":"precipitation","tag":"SPAN","xpath":"//*[@id=\"precipitation\"]"},"index":0,"tagName":"SPAN"}}]})
            print('[weather] [获取文本] [SNTag:20220916081744591285]  返回值：[' + str(type(lv_rain)) + ']' + str(lv_rain))
            #获取文本
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220916081744591300,Title:获取文本,Note:')
            lv_wind=ichrome_firefox.get_element_val_chrome(waitfor=10.000,title=r'中国气象局-天气预报-城市预报',url=r'https://weather.cma.cn/.*',continue_on_error='break',attrMap={"hasReachedRelativeAncestor":"false","nodeHierarchyInfo":[{"isPresentInSelector":1,"otherAttributes":{},"selectorInfo":{"attributes":{"css-selector":"#wind","id":"wind","tag":"SPAN","xpath":"//*[@id=\"wind\"]"},"index":0,"tagName":"SPAN"}}]})
            print('[weather] [获取文本] [SNTag:20220916081744591300]  返回值：[' + str(type(lv_wind)) + ']' + str(lv_wind))
            #拾取表格(web)
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220916081744591295,Title:拾取表格(web),Note:')
            lv_table1=ichrome_firefox.get_chrome_table(waitfor=10.000,title=r'中国气象局-天气预报-城市预报',url=r'https://weather.cma.cn/web/weather/.*',attrMap={"hasReachedRelativeAncestor":"false","nodeHierarchyInfo":[{"isPresentInSelector":1,"otherAttributes":{},"selectorInfo":{"attributes":{"css-selector":"#hourTable_0","id":"hourTable_0","tag":"TABLE","xpath":"//*[@id=\"hourTable_0\"]"},"index":0,"tagName":"TABLE"}}]},continue_on_error='break')
            print('[weather] [拾取表格(web)] [SNTag:20220916081744591295]  返回值：[' + str(type(lv_table1)) + ']' + str(lv_table1))
            #代码块
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220916081744591302,Title:代码块,Note:生成待发送excel')
            def procTem(s):
                '''
                格式化字符串
                '''
                return s.replace('℃','')
            
            
            ### 计算最高、最低温度和时间
            maxTemp = [lv_table1.iloc[2][1],lv_table1.iloc[0][1]]
            minTemp = [lv_table1.iloc[2][1],lv_table1.iloc[0][1]]
            
            for index in lv_table1.iloc[0].index:
                if index == 0:
                    continue
                if procTem(lv_table1.iloc[2][index]) > procTem(maxTemp[0]):
                    maxTemp = [lv_table1.iloc[2][index],lv_table1.iloc[0][index]]
                if procTem(lv_table1.iloc[2][index]) < procTem(minTemp[0]):
                    minTemp = [lv_table1.iloc[2][index],lv_table1.iloc[0][index]]
            
            
            ## 时间
            dateTnow = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            datenow = datetime.datetime.now().strftime("%Y-%m-%d ")
            datenext = (datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d ")
            nowH = datetime.datetime.now().hour
            nowY = datenow
            
            if int(maxTemp[1].split(':')[0]) < nowH:
                maxTemp[1] = datenext + maxTemp[1]
            else:
                maxTemp[1] = datenow + maxTemp[1]
            
            if int(minTemp[1].split(':')[0]) < nowH:
                minTemp[1] = datenext + minTemp[1]
            else:
                minTemp[1] = datenow + minTemp[1]
            
            ### 生成目标excel
            
            source_file = r'C:\Users\wangffeing\Desktop\RPAAS\0 需求\城市天气信息获取-XX城市.xlsx'
            target_file = r'C:\Users\wangffeing\Desktop\RPAAS\0 需求\城市天气信息获取-{0}.xlsx'.format(cityname)
            
            try:
            #    shutil.copy(source_file, target_file)+
                wb = openpyxl.load_workbook(source_file)
                sh = wb['天气信息']
                sh['A2'] = cityname
                sh['B2'] = dateTnow
                sh['C2'] = lv_temperature
                sh['D2'] = lv_rain
                sh['E2'] = lv_wind
                sh['F2'] = maxTemp[0]
                sh['G2'] = maxTemp[1]
                sh['H2'] = minTemp[0]
                sh['I2'] = minTemp[1]
                wb.save(target_file)
            except:
               print("无法生成天气excel文件:", sys.exc_info())
               
               
               
               
            #代码块
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220916081744591289,Title:代码块,Note:发送邮件')
            tmplstDate = datenow.split('-')
            mtitle = '{0}{1}年{2}月{3}日未来一段时间天气数据'.format(cityname,tmplstDate[0],tmplstDate[1],tmplstDate[2])
            mcontent = '{0}老师您好，附件为{1}{2}年{3}月{4}日未来一段时间天气数据，请查收！'.format(staff_name,cityname,tmplstDate[0],tmplstDate[1],tmplstDate[2])
            
            to_address = t_mail
            #to_address = 'goupingping@cmos.chinamobile.com'
            
            # 填写真实的发邮件服务器用户名、密码
            user = 'wangfeifeing@163.com'
            password = 'TFCFLFKGBUKGHNAY'
            # 邮件内容
            
            
            msg = MIMEMultipart()
            msg.attach(MIMEText(mcontent, 'plain', _charset="utf-8"))
            # 邮件主题描述
            msg["Subject"] = mtitle
            # 发件人显示，不起实际作用
            msg["from"] = 'wangfeifeing@163.com'
            # 收件人显示，不起实际作用
            msg["to"] = to_address
            # 抄送人显示，不起实际作用
            msg["Cc"] = ''
            
            att = MIMEText(mcontent, "plain", "utf-8")  # 使用UTF-8编码格式保证多语言的兼容性
            msg.attach(att)
            
            att1 = MIMEBase("application", "octet-stream")
            att1.set_payload(open(target_file, "rb").read())
            # 设置编码格式,附件重命名成xxx.docx
            att1.add_header("Content-Disposition", "attachment", filename=Header(target_file.split('\\')[-1], "utf-8").encode())
            encoders.encode_base64(att1)
            msg.attach(att1)
            
            # 发送邮件
            smtp = smtplib.SMTP_SSL("smtp.163.com", port=465)
            smtp.login(user=user, password=password)
            smtp.sendmail(user, to_address, msg.as_string())
            smtp.quit()
            
            #代码块
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220916081744591283,Title:代码块,Note:删除临时EXCEL & 关闭chrome')
            try:
                os.remove(target_file) # 这个可以删除单个文件，不能删除文件夹
            except BaseException as e:
                print(e)
                
            
        #代码块
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:weather,StepNodeTag:20220917162759642295,Title:代码块,Note:# 关闭chrome')
        # 关闭chrome
        cmd = "taskkill /f /t /im {}".format('chrome.exe')
        
        os.system(cmd)
      
    def Main(self):
        lv_datetime=None
        lv_temperature=None
        lv_rain=None
        lv_wind=None
        lv_table1=None
        #代码块
        self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:20220917160854951245,Title:代码块,Note:')
        bWeather = False
        bSalary = False
        # For循环
        self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:Main,StepNodeTag:20220917160807122225,Title:For循环,Note:# 2次循环')
        for iTimes in range(2):
            # Try异常
            self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:Main,StepNodeTag:20220917160807122223,Title:Try异常,Note:')
            try:
                #子流程
                self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:20220916092445651380,Title:子流程,Note:')
                tvar202209160924456513801=self.weather()
                print('[Main] [子流程] [SNTag:20220916092445651380]  返回值：[' + str(type(tvar202209160924456513801)) + ']' + str(tvar202209160924456513801))
                #代码块
                self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:20220917160928322248,Title:代码块,Note:')
                bWeather = True
                # Break中断
                self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:Main,StepNodeTag:20220917160845500243,Title:Break中断,Note:')
                break
            except Exception as e:
                # Continue继续
                self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:Main,StepNodeTag:20220917160807122224,Title:Continue继续,Note:')
                continue
            finally:
                pass
        # For循环
        self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:Main,StepNodeTag:20220917160951850250,Title:For循环,Note:# 2次循环')
        for iTimes in range(2):
            # Try异常
            self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:Main,StepNodeTag:20220917160951850252,Title:Try异常,Note:')
            try:
                #子流程
                self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:20220917161007094262,Title:子流程,Note:')
                tvar202209171610070942621=self.salary()
                print('[Main] [子流程] [SNTag:20220917161007094262]  返回值：[' + str(type(tvar202209171610070942621)) + ']' + str(tvar202209171610070942621))
                #代码块
                self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:20220917161012139263,Title:代码块,Note:')
                bSalary = True
                # Break中断
                self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:Main,StepNodeTag:20220917161103109274,Title:Break中断,Note:')
                break
            except Exception as e:
                # Continue继续
                self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:Main,StepNodeTag:20220917161048040271,Title:Continue继续,Note:')
                continue
            finally:
                pass
        # IF分支
        self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:Main,StepNodeTag:20220917161129422279,Title:IF分支,Note:')
        if bWeather & bSalary:
            #消息框
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:20220917161148435280,Title:消息框,Note:')
            tvar_20220917161148435281=ibox.msgs_box('处理完成',title=r'处理完成',timeout=0)
            print('[Main] [消息框] [SNTag:20220917161148435280]  返回值：[' + str(type(tvar_20220917161148435281)) + ']' + str(tvar_20220917161148435281))
        else:
            #代码块
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:20220917161159569287,Title:代码块,Note:')
            bWeather = False
            bSalary = False
            dateTnow = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            datenow = datetime.datetime.now().strftime("%Y-%m-%d ")
            
            mcontent= ''
            if bWeather == False:
                mcontent += ' 天气信息获取流程执行失败'
            if bSalary == False:
                mcontent += ' 员工实发工资计算流程执行失败'
                
            
            mtitle = 'RPA流程执行异常提示_' + dateTnow
            #代码块
            self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:20220917161221669288,Title:代码块,Note:发送邮件')
            
            to_address = 'goupingping@cmos.chinamobile.com'
            
            # 填写真实的发邮件服务器用户名、密码
            user = 'wangfeifeing@163.com'
            password = 'TFCFLFKGBUKGHNAY'
            # 邮件内容
            
            
            msg = MIMEMultipart()
            msg.attach(MIMEText(mcontent, 'plain', _charset="utf-8"))
            # 邮件主题描述
            msg["Subject"] = mtitle
            # 发件人显示，不起实际作用
            msg["from"] = 'wangfeifeing@163.com'
            # 收件人显示，不起实际作用
            msg["to"] = to_address
            # 抄送人显示，不起实际作用
            msg["Cc"] = ''
            
            att = MIMEText(mcontent, "plain", "utf-8")  # 使用UTF-8编码格式保证多语言的兼容性
            msg.attach(att)
            
            
            # 发送邮件
            smtp = smtplib.SMTP_SSL("smtp.163.com", port=465)
            smtp.login(user=user, password=password)
            smtp.sendmail(user, to_address, msg.as_string())
            smtp.quit()
            
 
if __name__ == '__main__':
    ILog.begin_init()
    robot_no = ''
    proc_no = ''
    job_no = ''
    input_arg = ''
    try:
        argv = sys.argv[1:]
        opts, args = getopt.getopt(argv,"hr:p:j:i:",["robot = ","proc = ","job = ","input = "])
    except getopt.GetoptError:
        print ('robot.py -r <robot> -p <proc> -j <job>')
    for opt, arg in opts:
        if opt == '-h':
            print ('robot.py -r <robot> -p <proc> -j <job>')
        elif opt in ("-r", "--robot"):
            robot_no = arg
        elif opt in ("-p", "--proc"):
            proc_no = arg
        elif opt in ("-j", "--job"):
            job_no = arg
        elif opt in ("-i", "--input"):
            input_arg = arg
    pro = RpaAsiM(robot_no=robot_no,proc_no=proc_no,job_no=job_no,input_arg=input_arg)
    pro.Main()
